// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()

function addData(bodydata, openid) {
  //console.log('addData: ' + bodydata.BMI);
  return db.collection('bodydata').add({
    data: {
      _openid: openid,
      BMI: bodydata.BMI,
      weight: bodydata.weight,
      height: bodydata.height,
      result: bodydata.result,
      date: new Date()
    }
  }) //db
}

function updateData(bodydata, id, openid) {
  console.log('update');
  return db.collection('bodydata')
    .doc(id)
    .update({
      data: {
        _openid: openid,
        BMI: bodydata.BMI,
        weight: bodydata.weight,
        height: bodydata.height,
        result: bodydata.result,
        date: new Date()
      }
    })
}
// 云函数入口函数
exports.main = async(event, context) => {
  const wxContext = cloud.getWXContext()
  var openid = wxContext.OPENID;
  var bodydata = {
    weight: event.weight,
    height: event.height,
    BMI: event.BMI,
    result: event.result
  }
  //保存该用户的的身高、体重 、BMI数据
  try {
    const rst = await db.collection('bodydata').orderBy('date', 'desc')
      .where({
        '_openid': openid
      }).get();
    return await Promise.all(rst.data).then(res => {
      var today = new Date();
      var date = res[0].date;

      //如果最新的记录为今天，则更新当天的记录，否则新增今日数据
      if (today.getFullYear() == date.getFullYear() && today.getMonth() == date.getMonth() && today.getDate() == date.getDate()) {
        return updateData(bodydata, res[0]._id, openid)
          .then(
            res => {
              console.log('云函数调用成功');
              return {
                result: res,
                errMsg: 'ok',
              }
            }
          )
          .catch(
            e => {
              console.log('云函数调用失败')
              console.error(e)
            }
          )
      } else {
        return addData(bodydata, openid)
          .then(
            res => {
              console.log('云函数调用成功');
              return {
                result: res,
                errMsg: 'ok',
              }
            }
          ) //then
          .catch(
            e => {
              console.log('云函数调用失败')
              console.error(e)
            }
          ) //catch
      }
    }) //await
  } catch (e) {
    conosle.log(e)
  }

}